<template>
  <div class="home-container">
    <!-- 管理员统计卡片 -->
    <el-row v-if="userStore.isAdmin" :gutter="20">
      <el-col :span="6" v-for="(stat, index) in statistics" :key="index">
        <el-card shadow="hover" :body-style="{ padding: '20px' }">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="40" :color="stat.color">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 公告区域 -->
    <div class="section announcement-section" :class="{ 'mt-0': !userStore.isAdmin }">
      <div class="section-header">
        <h3>最新公告</h3>
        <el-button type="primary" link @click="handleMoreAnnouncements">
          查看更多 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      <el-card v-loading="loading" class="announcement-card">
        <template v-if="announcements.length">
          <div
            v-for="item in announcements"
            :key="item.id"
            class="announcement-item"
            @click="handleAnnouncementClick(item)"
          >
            <div class="title">
              <el-icon><Bell /></el-icon>
              {{ item.title }}
            </div>
            <div class="time">{{ formatDate(item.createTime) }}</div>
          </div>
        </template>
        <el-empty v-else description="暂无公告" />
      </el-card>
    </div>

    <!-- 最新问卷 -->
    <div class="section questionnaire-section">
      <div class="section-header">
        <h3>最新问卷</h3>
        <el-button type="primary" link @click="$router.push('/questionnaire')">
          查看更多 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in questionnaires" :key="item.id">
          <el-card shadow="hover" class="questionnaire-card">
            <template #header>
              <div class="card-header">
                <span class="title">{{ item.title }}</span>
                <el-tag :type="getStatusType(item.status)">{{ getStatusText(item.status) }}</el-tag>
              </div>
            </template>
            <div class="card-content">
              <p class="description">{{ item.description || '暂无描述' }}</p>
              <div class="card-footer">
                <span class="time">{{ formatDate(item.createTime) }}</span>
                <el-button 
                  :type="item.status === 1 ? 'primary' : 'info'"
                  :disabled="item.status !== 1"
                  @click="handleFill(item)"
                >
                  {{ getButtonText(item) }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentAnnouncement?.title"
      width="50%"
    >
      <div class="announcement-content">{{ currentAnnouncement?.content }}</div>
      <div class="announcement-footer">
        发布时间：{{ formatDate(currentAnnouncement?.createTime) }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Document, User, Upload, View, Bell, ArrowRight } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'  // 导入用户状态
import { useRouter } from 'vue-router'  // 导入路由
import request from '../utils/request'
import { getList } from '@/api/announcement'
import { ElMessage } from 'element-plus'

const router = useRouter()  // 使用路由
const userStore = useUserStore()  // 使用用户状态

// 统计数据状态
const statsData = ref({
  questionnaireCount: 0,
  userCount: 0,
  todaySubmit: 0,
  totalVisits: 0
})

// 统计卡片配置
const statistics = computed(() => [
  {
    label: '问卷总数',
    value: statsData.value.questionnaireCount || 0,
    icon: 'Document',
    color: '#409EFF'
  },
  {
    label: '用户总数',
    value: statsData.value.userCount || 0,
    icon: 'User',
    color: '#67C23A'
  },
  {
    label: '今日提交',
    value: statsData.value.todaySubmit || 0,
    icon: 'Upload',
    color: '#E6A23C'
  },
  {
    label: '总访问量',
    value: statsData.value.totalVisits || 0,
    icon: 'View',
    color: '#F56C6C'
  }
])

const announcements = ref([])
const questionnaires = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentAnnouncement = ref(null)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadData = async () => {
  try {
    // 只有管理员才加载统计数据
    if (userStore.isAdmin) {
      const res = await request.get('/api/questionnaire/statistics')
      if (res.code === 200) {
        statsData.value = res.data
      }
    }

    // 加载最新公告（只显示最新的5条）
    const announcementRes = await getList({ page: 1, size: 5 })
    if (announcementRes.code === 200 && announcementRes.data) {
      announcements.value = announcementRes.data.records || []
    }

    // 加载最新问卷
    const questionnaireRes = await request.get('/api/questionnaire/latest')
    if (questionnaireRes.code === 200) {
      questionnaires.value = questionnaireRes.data
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 只在组件挂载时加载一次数据
onMounted(() => {
  loadData()
})

// 获取按钮文本
const getButtonText = (questionnaire) => {
  switch (questionnaire.status) {
    case 0: return '未发布'
    case 1: return '填写'
    case 2: return '已结束'
    default: return '未知'
  }
}

// 处理填写问卷
const handleFill = async (questionnaire) => {
  if (questionnaire.status === 1) {
    try {
      console.log('跳转到问卷填写页面:', questionnaire.id) // 添加调试日志
      await router.push({
        name: 'QuestionnaireFill',
        params: { id: questionnaire.id.toString() }  // 确保 id 是字符串
      })
    } catch (error) {
      console.error('导航失败:', error)
      ElMessage.error('导航失败')
    }
  }
}

const handleAnnouncementClick = (announcement) => {
  currentAnnouncement.value = announcement
  dialogVisible.value = true
}

// 添加状态类型和文本的方法
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '未发布'
    case 1: return '进行中'
    case 2: return '已结束'
    default: return '未知'
  }
}

// 处理"更多公告"按钮点击
const handleMoreAnnouncements = () => {
  router.push('/announcement')
}
</script>

<style lang="scss" scoped>
.home-container {
  padding: 20px;

  .section {
    margin-bottom: 30px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .stat-card {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-icon {
      padding: 16px;
      border-radius: 8px;
      background: #f5f7fa;
    }

    .stat-content {
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        line-height: 1.2;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }

  .announcement-card {
    .announcement-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      cursor: pointer;
      border-bottom: 1px solid #ebeef5;
      transition: all 0.3s;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
        padding-left: 10px;
      }

      .title {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
        margin-right: 20px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #303133;

        .el-icon {
          color: #409EFF;
        }
      }

      .time {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .questionnaire-card {
    margin-bottom: 20px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-weight: bold;
        font-size: 16px;
        color: #303133;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 70%;
      }
    }

    .card-content {
      .description {
        color: #606266;
        margin: 10px 0;
        height: 40px;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;

        .time {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
}

.announcement-content {
  padding: 20px 0;
  line-height: 1.6;
  white-space: pre-wrap;
  color: #606266;
}

.announcement-footer {
  text-align: right;
  color: #909399;
  font-size: 14px;
  margin-top: 20px;
}

.mt-0 {
  margin-top: 0;
}
</style> 